<template>
	<div>
		<CustomDialog
			:title="state.dialog.title"
			v-model:visible="state.dialog.isShowDialog"
			dialogWidth="900px"
			@close="closeDialog"
			:dialogFooterBtn="true"
		>
			<el-form ref="SecKillDialogFormRef" :model="state.ruleForm" size="default" label-width="180px">
				<el-form-item label="活动名称" prop="activityName" :rules="{ required: true, message: '活动名称不能为空', trigger: 'blue' }">
					<el-input v-model="state.ruleForm.activityName" placeholder="请输入活动名称" clearable></el-input>
				</el-form-item>

				<el-form-item label="活动时间" prop="activityTime" :rules="{ required: true, message: '活动时间不能为空', trigger: 'blue' }">
					<el-date-picker
						v-model="state.ruleForm.activityTime"
						type="datetimerange"
						range-separator="至"
						start-placeholder="开始时间"
						end-placeholder="结束时间"
					/>
				</el-form-item>

				<el-form-item label="预热时间" prop="activityPreTime" :rules="{ required: true, message: '预热时间不能为空', trigger: 'blue' }">
					<el-date-picker v-model="state.ruleForm.activityPreTime" type="datetime" placeholder="请选中预热时间" format="YYYY-MM-DD HH:mm:ss" />
				</el-form-item>
				<el-form-item label="是否包邮" prop="freeShipping">
					<el-switch
						v-model="state.ruleForm.freeShipping"
						inline-prompt
						active-text="包邮"
						inactive-text="不包邮"
						:active-value="1"
						:inactive-value="0"
					/>
				</el-form-item>
				<el-form-item label="秒杀销量展示" prop="salesShowType">
					<el-radio-group v-model="state.ruleForm.salesShowType">
						<el-radio :label="0">真实活动销量</el-radio>
						<el-radio :label="1">商品总销量(包含虚拟商品)</el-radio>
					</el-radio-group>
				</el-form-item>

				<el-form-item label="限购数量" prop="purchaseLimit" :rules="{ required: true, message: '限购数量不能为空', trigger: 'blue' }">
					<el-input v-model="state.ruleForm.purchaseLimit" placeholder="请输入限购数量" clearable type="number" min="1">
						<template #append>
							<div class="cursor-pointer">个</div>
						</template>
					</el-input>
				</el-form-item>

				<el-form-item label="订单支付时间" prop="paymentTimes" :rules="{ required: true, message: '订单支付时间不能为空', trigger: 'blue' }">
					<el-input v-model="state.ruleForm.paymentTimes" placeholder="请输入订单支付时间" clearable type="number" min="1">
						<template #append>
							<div class="cursor-pointer">分钟</div>
						</template>
					</el-input>
				</el-form-item>

				<el-form-item label="活动说明" prop="activityDesc">
					<el-input v-model="state.ruleForm.activityDescTitle" placeholder="请选择活动说明">
						<template #append>
							<div class="cursor-pointer" @click="openRichTextDialog">选择活动说明</div>
						</template>
					</el-input>
				</el-form-item>
				<el-form-item label="活动商品">
					<el-button type="primary" link @click="addItem"> +添加商品</el-button>
				</el-form-item>
				<el-form-item>
					<div class="item-content">
						<div v-if="state.items.length > 0" class="flex item-header">
							<div class="content">商品信息</div>
							<div class="oper">设置</div>
							<div class="oper">操作</div>
						</div>
						<div>
							<div class="flex item-body" v-for="(item, index) in state.items">
								<div class="content flex">
									<div class="goods-img">
										<img :src="STATIC_URL + item.image" alt="" class="goods-img" />
									</div>
									<div class="goods-content">
										<div class="goods-title cursor-pointer" :title="item.title">{{ item.title }}</div>
										<div class="goods-price">{{ item.price }}元</div>
									</div>
								</div>
								<div class="oper">
									<el-button type="primary" link @click="setItem(index)">设置商品</el-button>
								</div>
								<div class="oper">
									<el-button type="danger" link @click="removeItem(index)">移除</el-button>
								</div>
							</div>
						</div>
					</div>
				</el-form-item>
				<!--				</div>-->
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit(SecKillDialogFormRef)" size="default">{{ state.dialog.submitTxt }}</el-button>
				</span>
			</template>
		</CustomDialog>
		<ItemDialog ref="ItemChoiceRef" @choice="choiceItem"></ItemDialog>
		<ItemSetDialog ref="ItemSetDialogRef"></ItemSetDialog>
		<ChoiceRichTextDialog ref="ChoiceRichTextDialogRef" @choice="choiceRichText"></ChoiceRichTextDialog>
	</div>
</template>

<script setup lang="ts">
import { reactive, ref, defineAsyncComponent } from 'vue';
import { type FormInstance, type FormRules } from 'element-plus';
import msg from '/@/utils/messageUtils';
import { STATIC_URL } from '/@/utils/config';
import { SecKillApi } from '/@/api/shop/seckill';
import _ from 'lodash';
import messageUtils from '/@/utils/messageUtils';
const ItemDialog = defineAsyncComponent(() => import('/@/views/goods/goods/choice/index.vue'));

const ItemSetDialog = defineAsyncComponent(() => import('./item_set_dialog.vue'));
const ChoiceRichTextDialog = defineAsyncComponent(() => import('/@/views/shop/data/richtext/choice/index.vue'));
const ChoiceRichTextDialogRef = ref();

const ItemChoiceRef = ref();
const ItemSetDialogRef = ref();
const SecKillDialogFormRef = ref();
const emit = defineEmits(['refresh']);
const state = reactive({
	ruleForm: {
		id: '',
		activityTime: [] as any,
		activityName: '',
		startTime: '',
		endTime: '',
		activityPreTime: '',
		freeShipping: 0, // 是否包邮 0:不包邮，1:包邮
		purchaseLimit: 0,
		paymentTimes: 0,
		salesShowType: 0,
		activityDescId: '',
		activityDescTitle: '',
		discountConditions: [] as any,
	},
	discountTypeDisabled: false,
	items: [] as any,
	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitTxt: '',
	},
});

const onCancel = () => {
	closeDialog();
};

const openRichTextDialog = () => {
	ChoiceRichTextDialogRef.value.openDialog();
};

const choiceRichText = (choiceRichText: ChoiceRichText) => {
	console.log('choiceRichText: ', choiceRichText);
	state.ruleForm.activityDescId = choiceRichText.id;
	state.ruleForm.activityDescTitle = choiceRichText.title;
};

const choiceItem = (choiceGoodsItems: ChoiceGoodsItem[]) => {
	console.log('choiceGoodsItem: ', choiceGoodsItems);
	choiceGoodsItems.forEach((choiceGoodsItem) => {
		state.items.push({
			goodsId: choiceGoodsItem.id,
			image: choiceGoodsItem.image,
			title: choiceGoodsItem.title,
			subTitle: choiceGoodsItem.subTitle,
			price: choiceGoodsItem.price,
			originalPrice: choiceGoodsItem.originalPrice,
			stock: choiceGoodsItem.stock,
			sales: choiceGoodsItem.sales,
			itemProps: [],
		});
	});
};

const setItem = (index: number) => {
	console.log('goods  setting: ', index, 'state.items[index]: ', state.items[index]);
	ItemSetDialogRef.value.openDialog(state.items[index]);
};

const removeItem = (index: number) => {
	state.items.splice(index, 1);
};

const addItem = () => {
	ItemChoiceRef.value.openDialog();
};
// 关闭弹窗
const closeDialog = () => {
	SecKillDialogFormRef.value.resetFields();
	state.dialog.isShowDialog = false;
	clearArraysContent();
	state.ruleForm.activityName = '';
	state.ruleForm.activityTime = [];
};

const checkGoodsSeting = () => {
	const check = _.every(state.items, (e) => {
		if (_.isEmpty(e.itemProps)) {
			messageUtils().error(`商品-[${e.title}]-没有进行设置信息,请全部设置信息后再提交`);
			return false;
		}
		return true;
	});
	return check;
};
const onSubmit = async (formEl: FormInstance | undefined) => {
	const activityTime = state.ruleForm.activityTime;
	if (!formEl) return;
	await formEl.validate(async (valid) => {
		if (valid) {
			if (!checkGoodsSeting()) {
				return;
			}
			try {
				const ids = state.items.map((e: any) => e.id);
				if (state.dialog.type === 'add') {
					await SecKillApi().create({
						activityName: state.ruleForm.activityName,
						activityStartTime: activityTime[0].getTime(),
						activityEndTime: activityTime[1].getTime(),
						activityPreTime: state.ruleForm.activityPreTime.getTime(),
						freeShipping: state.ruleForm.freeShipping,
						purchaseLimit: state.ruleForm.purchaseLimit,
						paymentTimes: state.ruleForm.paymentTimes,
						activityDescId: state.ruleForm.activityDescId,
						activityDescTitle: state.ruleForm.activityDescTitle,
						salesShowType: state.ruleForm.salesShowType,
						items: state.items,
					});
				} else {
					await SecKillApi().update({
						id: state.ruleForm.id,
						activityName: state.ruleForm.activityName,
						activityStartTime: resolveTime(activityTime[0]),
						activityEndTime: resolveTime(activityTime[1]),
						activityPreTime: resolveTime(state.ruleForm.activityPreTime),
						freeShipping: state.ruleForm.freeShipping,
						purchaseLimit: state.ruleForm.purchaseLimit,
						paymentTimes: state.ruleForm.paymentTimes,
						activityDescId: state.ruleForm.activityDescId,
						activityDescTitle: state.ruleForm.activityDescTitle,
						salesShowType: state.ruleForm.salesShowType,
						items: state.items,
					});
				}
				msg().success('操作成功');
				closeDialog();
				emit('refresh');
			} catch (e) {
				console.log('e: ', e);
				// msg().error('操作失败');
			}
		}
	});
};

const openDialog = async (type: string, id: string) => {
	if (type === 'edit') {
		state.dialog.title = '修改秒杀活动';
		state.dialog.submitTxt = '修 改';
		state.dialog.type = 'edit';
		state.ruleForm.id = id;
		console.log('id: ', id);
		const { data } = await SecKillApi().view(id);
		state.ruleForm.id = id;
		state.ruleForm.activityName = data.activityName;
		state.ruleForm.activityTime = [data.activityStartTime, data.activityEndTime];
		state.ruleForm.activityPreTime = data.activityPreTime;
		state.ruleForm.freeShipping = data.freeShipping;
		state.ruleForm.purchaseLimit = data.purchaseLimit;
		state.ruleForm.paymentTimes = data.paymentTimes;
		state.ruleForm.salesShowType = data.salesShowType;
		state.ruleForm.activityDescId = data.activityDescId;
		state.ruleForm.activityDescTitle = data.activityDescTitle;
		state.items = data.secKillItems;
	} else {
		state.dialog.title = '新增秒杀活动';
		state.dialog.submitTxt = '新 增';
		state.dialog.type = type;
		// nextTick(() => {
		// 	discountDialogFormRef.value.resetFields();
		// 	discountDialogFormRef.value.clearValidate();
		// });
		state.ruleForm.activityName = '';
		state.ruleForm.activityTime = [];
	}
	state.dialog.isShowDialog = true;
};

const resolveTime = (time: any) => {
	const contentType = typeof time;
	if (contentType == 'string') {
		return new Date(time).getTime();
	}
	return time.getTime();
};

const clearArraysContent = () => {
	state.items = [];
	// SecKillDialogFormRef.value.resetFields();
	// state.ruleForm.salesShowType = 0;
	state.ruleForm.activityPreTime = '';
	state.ruleForm.freeShipping = 0;
	state.ruleForm.purchaseLimit = 0;
	state.ruleForm.paymentTimes = 0;
	state.ruleForm.salesShowType = 0;
	// state.ruleForm.activityDesc = '';
};
defineExpose({ openDialog });
</script>

<style scoped>
.item-content {
	width: 400px;
}

.exec-width {
	width: 250px;
	margin-left: 10px;
}

.item-header {
	background-color: rgba(223, 230, 233, 1);
}

.item-body {
	margin-top: 10px;
}

.content {
	flex: 1;
}

.oper {
	width: 60px;
	margin-left: 5px;
}

.goods-img {
	width: 50px;
	height: 50px;
}

.goods-content {
	margin-left: 10px;
	flex: 1;

	.goods-title {
		font-size: 14px;
		height: 20px;
		line-height: 20px;
		overflow: hidden;
		text-overflow: ellipsis;
		/* white-space: nowrap; */
		/* text-overflow: ellipsis; */
		display: -webkit-box;
		-webkit-line-clamp: 1;
		-webkit-box-orient: vertical;
		padding-right: 5px;
	}

	.goods-price {
		font-size: 12px;
		height: 20px;
		line-height: 40px;
		color: rgba(255, 118, 117, 1);
	}
}
</style>
